<?php
// 显示所有错误
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 加载数据库配置
require_once __DIR__ . '/../config/database.php';

$message = '';
$success = true;

try {
    // 创建PDO连接
    $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
    $pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $message .= "<div class='alert alert-success'>数据库连接成功！</div>";
    
    // 创建测试用户
    $pdo->exec("
        INSERT IGNORE INTO `".DB_PREFIX."users` 
        (id, username, password, email, nickname, role, status, created_at, updated_at) VALUES 
        (100, 'test_user', '".password_hash('password123', PASSWORD_DEFAULT)."', 'test@example.com', '测试用户', 'user', 'active', DATE_SUB(NOW(), INTERVAL 30 DAY), NOW()),
        (101, 'child_user1', '".password_hash('password123', PASSWORD_DEFAULT)."', 'child1@example.com', '小明', 'user', 'active', DATE_SUB(NOW(), INTERVAL 20 DAY), NOW()),
        (102, 'child_user2', '".password_hash('password123', PASSWORD_DEFAULT)."', 'child2@example.com', '小红', 'user', 'active', DATE_SUB(NOW(), INTERVAL 15 DAY), NOW()),
        (103, 'child_user3', '".password_hash('password123', PASSWORD_DEFAULT)."', 'child3@example.com', '小华', 'user', 'active', DATE_SUB(NOW(), INTERVAL 10 DAY), NOW()),
        (104, 'new_child', '".password_hash('password123', PASSWORD_DEFAULT)."', 'newchild@example.com', '新用户', 'user', 'active', NOW(), NOW())
    ");
    
    $message .= "<div class='alert alert-success'>测试用户添加成功！</div>";
    
    // 获取游戏ID
    $games = $pdo->query("SELECT id, name FROM `".DB_PREFIX."games`")->fetchAll(PDO::FETCH_ASSOC);
    if (count($games) == 0) {
        throw new Exception("没有找到游戏数据，请先运行setup_tables.php创建基础数据");
    }
    
    // 为用户添加游戏记录
    $gameRecords = [];
    $users = [100, 101, 102, 103]; // 测试用户ID
    
    // 为每个用户添加游戏记录
    foreach ($users as $userId) {
        foreach ($games as $game) {
            // 每个游戏添加多条记录，不同分数和时间
            for ($i = 0; $i < rand(3, 8); $i++) {
                $score = rand(30, 100);
                $duration = rand(30, 300); // 30秒到5分钟
                $daysAgo = rand(1, 30); // 1-30天前
                
                $gameRecords[] = [
                    $userId, 
                    $game['id'], 
                    $score, 
                    $duration, 
                    date('Y-m-d H:i:s', strtotime("-$daysAgo days +".rand(0, 23)." hours +".rand(0, 59)." minutes"))
                ];
            }
        }
    }
    
    // 批量插入游戏记录
    $stmt = $pdo->prepare("INSERT INTO `".DB_PREFIX."game_records` (user_id, game_id, score, duration, played_at) VALUES (?, ?, ?, ?, ?)");
    
    foreach ($gameRecords as $record) {
        $stmt->execute($record);
    }
    
    $recordCount = count($gameRecords);
    $message .= "<div class='alert alert-success'>已添加 $recordCount 条游戏记录！</div>";
    
    // 获取成就ID
    $achievements = $pdo->query("SELECT id, name FROM `".DB_PREFIX."achievements`")->fetchAll(PDO::FETCH_ASSOC);
    if (count($achievements) == 0) {
        throw new Exception("没有找到成就数据，请先运行setup_tables.php创建基础数据");
    }
    
    // 为用户解锁成就
    $userAchievements = [];
    
    foreach ($users as $userId) {
        // 随机选择一些成就解锁
        $achievementCount = rand(2, count($achievements));
        $userAchievementIds = array_rand(array_flip(array_column($achievements, 'id')), $achievementCount);
        
        if (!is_array($userAchievementIds)) {
            $userAchievementIds = [$userAchievementIds];
        }
        
        foreach ($userAchievementIds as $achievementId) {
            $daysAgo = rand(1, 25); // 1-25天前
            $gameId = $games[array_rand($games)]['id']; // 随机选择一个游戏
            
            $userAchievements[] = [
                $userId,
                $achievementId,
                $gameId,
                date('Y-m-d H:i:s', strtotime("-$daysAgo days +".rand(0, 23)." hours +".rand(0, 59)." minutes"))
            ];
        }
    }
    
    // 批量插入用户成就
    $stmt = $pdo->prepare("INSERT IGNORE INTO `".DB_PREFIX."user_achievements` (user_id, achievement_id, game_id, unlocked_at) VALUES (?, ?, ?, ?)");
    
    foreach ($userAchievements as $achievement) {
        $stmt->execute($achievement);
    }
    
    $achievementCount = count($userAchievements);
    $message .= "<div class='alert alert-success'>已添加 $achievementCount 条用户成就记录！</div>";
    
    // 更新管理员最后登录时间
    $pdo->exec("UPDATE `".DB_PREFIX."users` SET last_login = NOW() WHERE role = 'admin'");
    
    $message .= "<div class='alert alert-success'><strong>所有测试数据添加成功！</strong> 现在您可以<a href='index.php' class='alert-link'>返回管理后台</a>查看数据。</div>";
    
} catch (PDOException $e) {
    $success = false;
    $message .= "<div class='alert alert-danger'><strong>错误：</strong> " . $e->getMessage() . "</div>";
} catch (Exception $e) {
    $success = false;
    $message .= "<div class='alert alert-danger'><strong>错误：</strong> " . $e->getMessage() . "</div>";
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KidsMind - 添加测试数据</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">KidsMind 添加测试数据</h4>
                    </div>
                    <div class="card-body">
                        <h5 class="card-title mb-4">测试数据添加结果</h5>
                        
                        <?php echo $message; ?>
                        
                        <div class="mt-4">
                            <?php if ($success): ?>
                                <a href="index.php" class="btn btn-primary">进入管理后台</a>
                            <?php else: ?>
                                <a href="add_test_data.php" class="btn btn-warning">重试</a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html> 